package com.lyb.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.lyb.spzx.model.entity.product.Category;
import com.lyb.spzx.product.mapper.CategoryMapper;
import com.lyb.spzx.product.service.CategoryService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Category> findACategory() {
        //先从Redis获取
        String categorie = redisTemplate.opsForValue().get("category:one");
        if (!StringUtils.isEmpty(categorie)){
            List<Category> categories = JSON.parseArray(categorie, Category.class);
            return categories;
        }
        List<Category> categoryList =  categoryMapper.findACategory();
        //保存到Redis
        redisTemplate.opsForValue().set("category:one", JSON.toJSONString(categoryList),7, TimeUnit.DAYS);
        return categoryList;
    }

    @Override
    public List<Category> findAllCategory() {
        List<Category> categories = categoryMapper.findAllCategory();
        //全部一级分类
        List<Category> categories1 = categories.stream()
                .filter(category -> category.getParentId().longValue() == 0)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(categories1)){
           categories1.forEach(category -> {
               List<Category> categories2 = categories.stream().filter(item ->
                   item.getParentId().longValue() == category.getId().longValue()
               ).collect(Collectors.toList());
               category.setChildren(categories2);

               if (!CollectionUtils.isEmpty(categories2)){
                   categories2.forEach(category2 -> {
                       List<Category> categories3 = categories.stream().filter(item ->
                               item.getParentId().longValue() == category2.getId().longValue())
                               .collect(Collectors.toList());
                       category2.setChildren(categories3);
                   });
               }
           });

        }

        return categories1;
    }
}
